package com.tg.app.playback;

import android.content.Context;
import android.os.Build;
import android.text.TextUtils;

import com.appbase.custom.constant.EventConstants;
import com.appbase.custom.constant.PlaybackConstants;
import com.demo.view.TimeRuleView;
import com.tg.app.camera.Camera;
import com.tange.base.toolkit.DateUtil;
import com.tg.appcommon.android.TGLog;
import com.tg.data.http.entity.AVFrames;
import com.tg.data.media.OnICameraAVListener;
import com.tg.data.media.OnICameraListener;
import com.tg.data.media.OnICameraPlaybackListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Describe:
 * Created by Rance Rang on 2019-09-15.
 * <p>
 * Copyright (c) Tange.Inc All rights reserved.
 */
public class CameraPlayback extends TGPlayback implements OnICameraListener, OnICameraAVListener, OnICameraPlaybackListener {

    public CameraPlayback(Context context, Camera camera) {
        super(context, camera);
        camera.setPlaybackListener(this);
    }

    @Override
    public void getRecordList(String day) {
        super.getRecordList(day);
        if (camera != null && !TextUtils.isEmpty(day)) {
            camera.playback_GetRecordList(day);
        }
    }

    @Override
    public void stopAudio() {
        camera.stopAudio();
    }

    @Override
    public void stopShow() {
        camera.playback_stopShow();
    }

    @Override
    public void setSpeed(int speed) {
        super.setSpeed(speed);
        if (camera != null && !camera.isRunningLiveVideo()) {
            camera.playback_speed(speed);
        }
    }

    @Override
    public void clear() {

    }

    @Override
    public void destroy() {
        camera.setPlaybackListener(null);
    }

    @Override
    public void playbackRecord(long time) {
        super.playbackRecord(time);
        if (camera != null && time > 0) {
            camera.playback_PlayRecord(time);
            setSpeed(this.speed);
        }

    }

    @Override
    public void startAudio() {
        camera.startAudio();
    }

    @Override
    public void receiveUpdateConnectStates(int state) {
        if (state == Camera.CONNECTION_STATE_CONNECTED) {
            getRecordList(day);
        }
    }

    @Override
    public void receiveIOCtrlData(int iotype, byte[] data) {
// SD卡回放列表 某一天的
//        if (iotype == AVIOCTRLDEFs.IOTYPE_USEREX_IPCAM_LISTEVENT_RESP) {
////            int channel = Packet.byteArrayToInt_Little(data, 0); // Camera Index
////            int num = Packet.byteArrayToInt_Little(data, 4);
////            byte index = data[8];
//            byte endFlag = data[9];
//            byte countTmp = data[10];
//            int count = countTmp >= 0? countTmp : 256 + countTmp;
////            byte reserved = data[11];
//            int dayOfMonth = DateUtil.getCalendarDayOfMonth(day);
//            if (count > 0) {
//                for (int i = 0; i < count; i++) {
//                    int pos = 16 * i + 12; // sAvExEvents 16位，其它开始内容共12位
//                    if (data.length < pos + 12){
//                        break;
//                    }
//                    byte[] timeDay = new byte[8];
//                    System.arraycopy(data, pos, timeDay, 0, 8);
//                    AVIOCTRLDEFs.STimeDay sTimeDays = new AVIOCTRLDEFs.STimeDay(timeDay);
//                    int file_len = Packet.byteArrayToInt_Little(data, pos + 8);
//                    byte event = data[pos + 12];
//                    TimeRuleView.TimePart part = new TimeRuleView.TimePart();
//                    part.startTime = sTimeDays.hour * 3600 + sTimeDays.minute * 60 + sTimeDays.second;
//                    if (sTimeDays.hour == 23&&dayOfMonth>sTimeDays.day) {
//                        file_len = file_len -(86400- part.startTime);
//                        part.startTime = 0;
//                    }
//                    if (part.startTime<0){
//                        part.startTime = 0;
//                    }
//                    part.endTime = part.startTime + file_len;
//                    getPartStartTime(event, part);
//                    if (event > 0) {
//                        EventMessageBean eventMessageBean = new EventMessageBean();
//                        eventMessageBean.setStart_time(String.format("%s %s", this.day, DateUtil.formatTimeHHmmss(part.startTime)));
//                        eventMessageBean.setEnd_time(String.format("%s %s", this.day, DateUtil.formatTimeHHmmss(part.endTime)));
//                        eventMessageBean.setTag(part.eventType);
//                        getEventList().add(eventMessageBean);
//                    }
//                    getRecordTimes().add(part);
//                    timeRuleList.add(part);
//                }
//                //列表没有发送完，不刷新
//                if (endFlag == 0) return;
//
//            }
//            ArrayList<TimeRuleView.TimePart>  parts = sortTimePart(timeRuleList);
//            timeRuleList.clear();
//            timeRuleList.addAll(parts);
//            outputVideoInfo();
//
//            if (playbackMediaListener != null) {
//                playbackMediaListener.onPlaybackRecordListResp(false);
//            }
//        }

//        if (playbackMediaListener != null) {
//            playbackMediaListener.onPlaybackRecordListResp(false);
//        }
    }

    private void outputVideoInfo(){
        for (TimeRuleView.TimePart timePart : timeRuleList){
            TGLog.d("CameraPlayback", "startTime:" + timePart.startTime + "endTime:" + timePart.endTime + ", sTime:" +DateUtil.formatTimeHHmmss(timePart.startTime) + ", eTime:" +DateUtil.formatTimeHHmmss(timePart.endTime));
        }
    }

    private ArrayList<TimeRuleView.TimePart> sortTimePart(List<TimeRuleView.TimePart> timeParts) {
        ArrayList<TimeRuleView.TimePart>  parts = new ArrayList<TimeRuleView.TimePart>(timeParts);
        try {
            Comparator<TimeRuleView.TimePart> comparator = (part, t1) -> {
                //1 后向前
                if (t1.startTime > part.startTime) {
                    return -1;
                } else if (t1.startTime < part.startTime) {
                    return 1;
                }
                return 0;
            };
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                parts.sort(comparator);
            } else {
                Collections.sort(parts, comparator);
            }
        }catch (Exception e){

        }

        return parts;
    }

    private void getPartStartTime(byte event, TimeRuleView.TimePart part) {
        if (event == PlaybackConstants.ECEVENT_HUMAN_BODY) {
            part.eventType = EventConstants.BODY;
//            part.startTime -=5;
        } else if (event == PlaybackConstants.ECEVENT_MOTION_DETECTED) {
            part.eventType = EventConstants.MOTION;
        } else if (event == PlaybackConstants.ECEVENT_SOUND) {
            part.eventType = EventConstants.SOUND;
        } else if (event == PlaybackConstants.ECEVENT_GENERIC_SENSOR) {
            part.eventType = EventConstants.GSENSOR;
        } else if (event > 3) {
            part.eventType = "other";
        }
    }

    @Override
    public void receiveVideoData(AVFrames avFrames) {
        if (isStop()) return;
        if (this.playbackMediaListener != null) {
            playbackMediaListener.onPlaybackVideoData(avFrames);
        }
    }

    @Override
    public void receiveSubVideoData(AVFrames avFrame) {
        if (this.playbackMediaListener != null) {
            playbackMediaListener.onPlaybackVideoData(avFrame);
        }
    }

    @Override
    public void receiveAudioData(AVFrames avFrames) {
        if (isStop()) return;
        if (this.playbackMediaListener != null) {
            playbackMediaListener.onPlaybackAudioData(avFrames);
        }
    }

    @Override
    public void receivePlaybackNext(long pts) {
        if (this.playbackMediaListener != null) {
            playbackMediaListener.onPlaybackSDNextTimePart(pts);
        }
    }
}
